﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PInitiatives.Models;


namespace PInitiatives
{
    public class InitiativeAccessDeniedAuthorizeAttribute : AuthorizeAttribute
    {
        int initiativeId;
        PInitiativesEntities _db = new PInitiativesEntities();

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

            //HttpContext ctx = HttpContext.Current;

            //string cookie = ctx.Request.Cookies["MyCookie"];

            //HttpCookie c = Request.Cookies["MyCookie"];


            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult("~/Account/Logon?returnUrl=" + filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.RawUrl));
                return;
            }

            initiativeId = int.Parse(filterContext.RouteData.Values["id"].ToString());
            if (_db.Initiatives.Find(initiativeId) == null)
            {
                filterContext.Result = new RedirectResult("~/Initiative/Browse");
            }
            else if (_db.Initiatives.Find(initiativeId).InitiativeAuthor.aspnet_Users.UserName != filterContext.HttpContext.User.Identity.Name)
            {
                filterContext.Result = new RedirectResult("~/Account/AccessDenied");
            }

        }
    }
}